<template>
  <a-drawer
    :width="900"
    placement="right"
    :closable="false"
    @close="close"
    :visible="visible"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <div class="row">
          <h1 class="title">退货申请单： {{ this.model.id }}</h1>
          <h1 class="title">&emsp;&emsp;&emsp;申请状态： {{ this.model.status_dictText }}</h1>
        </div>
        <detail-list>
          <detail-list-item term="退货类型">{{ this.model.returnType_dictText ? this.model.returnType_dictText : "-" }}</detail-list-item>
          <detail-list-item term="货品状态">{{ this.model.productStatus_dictText ? this.model.productStatus_dictText : "-" }}</detail-list-item>
          <detail-list-item term="钱款状态">{{ this.model.moneyStatus_dictText ? this.model.moneyStatus_dictText : "-" }}</detail-list-item>
        </detail-list>

        <a-table
          style="margin-bottom: 10px"
          rowKey="id"
          bordered
          :scroll="{ x: 800 }"
          :columns="omsOrderReturnItemTable.columns"
          :pagination="false"
          :dataSource="omsOrderReturnItemTable.dataSource">

        </a-table>

        <a-card :bordered="true">
          <detail-list title="申请信息">
            <detail-list-item term="订单编号">{{ this.model.orderId }}</detail-list-item>
            <detail-list-item term="用户账号">{{ this.model.memberId }}</detail-list-item>
            <detail-list-item term="退货类型">{{ this.model.returnType_dictText ? this.model.returnType_dictText : "-"  }}</detail-list-item>
            <detail-list-item term="申请时间">{{ this.model.createTime }}</detail-list-item>
            <detail-list-item term="联系人">  {{ this.model.returnName ? this.model.returnName : "-"   }}</detail-list-item>
            <detail-list-item term="联系电话">{{ this.model.returnPhone ? this.model.returnPhone : "-" }}</detail-list-item>
            <detail-list-item term="退货原因">{{ this.model.reason ? this.model.reason : "-"  }}</detail-list-item>
            <detail-list-item term="单号申请次数">{{ this.model.returnApplyIndex ? this.model.returnApplyIndex : "-"  }}</detail-list-item>
            <detail-list-item term="退货的系统">{{ this.model.sourceSystem_dictText ? this.model.sourceSystem_dictText : "-" }}</detail-list-item>
            <detail-list-item term="问题描述">{{ this.model.description ? this.model.description : "-"  }}</detail-list-item>
            <detail-list-item term="凭证图片">{{ this.model.proofPics ? this.model.proofPics : "-"  }}</detail-list-item>
          </detail-list>

          <a-divider style="margin-bottom: 24px"/>
          <detail-list title="退款信息">

            <div class="row" :hidden="(this.model.status===0 || (this.model.status===1 && this.model.moneyStatus < 2 ) )">
              <detail-list-item term="扣除费用">{{ this.model.deductAmount ? this.model.deductAmount : "-" }}</detail-list-item>
              <detail-list-item term="扣除原因">{{ this.model.deductReason ? this.model.deductReason : "-" }}</detail-list-item>
            </div>

            <div class="row" :hidden="(!(this.model.status===0 || (this.model.status===1 && this.model.moneyStatus < 2 ) ))">
              <a-form-item
                :labelCol="{ xs: { span: 24 },sm: { span: 10},}"
                :wrapperCol="{ xs: { span: 24 }, sm: { span: 14},}"
                label="扣除费用">
                <a-input-number :min="0" @change="onDeductAmountChange" placeholder="请输入扣除费用" v-decorator="['deductAmount', {}]" />
              </a-form-item>
              <a-form-item
                :labelCol="{ xs: { span: 24 },sm: { span: 10},}"
                :wrapperCol="{ xs: { span: 24 }, sm: { span: 14},}"
                label="扣除原因">
                <a-input placeholder="请输入扣除原因" v-decorator="['deductReason', {}]"/>
              </a-form-item>
            </div>

            <detail-list-item term="退款金额">{{ this.model.returnAmount ? this.model.returnAmount : "-" }}</detail-list-item>
            <detail-list-item term="快速退款">{{ this.model.fastReturnType ? this.model.fastReturnType : "-" }}</detail-list-item>


          </detail-list>

          <a-divider style="margin-bottom: 24px"/>
          <detail-list title="物流信息">
            <detail-list-item term="物流公司">{{ this.model.deliveryCompany ? this.model.deliveryCompany : "-" }}</detail-list-item>
            <detail-list-item term="物流单号">{{ this.model.deliverySn ? this.model.deliverySn : "-" }}</detail-list-item>
          </detail-list>

          <a-divider style="margin-bottom: 24px"/>
          <detail-list title="收货信息">

            <a-form-item :hidden="this.model.status!==0"
              :labelCol="{ xs: { span: 24 },sm: { span: 5},}"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 10},}"
              label="选择收货点">
              <j-dict-select-tag @change="handleChangeCompanyAddress" size="small" v-decorator="['companyAddressId', {}]" placeholder="请选择收货点" dictCode="oms_company_address,address_name,id" :triggerChange="true"/>
            </a-form-item>
            <detail-list-item term="收货人">{{ this.model.receiveMan ? this.model.receiveMan : "-" }}</detail-list-item>
            <detail-list-item term="收货人电话">{{ this.model.receivePhone ? this.model.receivePhone : "-" }}</detail-list-item>
            <detail-list-item term="收货地区"> {{ this.model.receiveProvince }} - {{ this.model.receiveCity }} - {{ this.model.receiveRegion }} </detail-list-item>
            <detail-list-item term="详细地址">{{ this.model.receiveDetailAddress ? this.model.receiveDetailAddress : "-" }}</detail-list-item>
            <detail-list-item term="收货时间">{{ this.model.receiveTime  ? this.model.receiveTime : "-"   }}</detail-list-item>
            <detail-list-item term="收货备注">{{ this.model.receiveNote ? this.model.receiveNote : "-"  }}</detail-list-item>
          </detail-list>

          <detail-list :hidden="(!(this.model.status===1 && (this.model.productStatus!==0 && this.model.productStatus!==4 && this.model.productStatus!==5)))">
            <a-form-item
              :labelCol="{ xs: { span: 24 },sm: { span: 5},}"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 16},}"
              :hidden="(!(this.model.status===1 && (this.model.productStatus!==0 && this.model.productStatus!==4 && this.model.productStatus!==5)))"
              label="收货备注">
              <a-textarea placeholder="请输入处理备注" v-decorator="['receiveNote', {}]" :rows="2"/>
            </a-form-item>
          </detail-list>

          <a-divider style="margin-bottom: 24px"/>
          <detail-list title="处理信息" :hidden="this.model.status===0">
            <detail-list-item term="处理人员">{{ this.model.handleMan }}</detail-list-item>
            <detail-list-item term="处理时间">{{ this.model.handleTime }}</detail-list-item>
            <detail-list-item term="处理备注">{{ this.model.handleNote }}</detail-list-item>
          </detail-list>
          <detail-list title="处理信息" :hidden="this.model.status!==0">
            <a-form-item
              :labelCol="{ xs: { span: 24 },sm: { span: 5},}"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 16},}"
              label="处理备注">
              <a-textarea placeholder="请输入处理备注" v-decorator="['handleNote', {}]" :rows="2"/>
            </a-form-item>
          </detail-list>
        </a-card>
      </a-form>
    </a-spin>
    <div :style="{textAlign: 'center',marginTop: '15px'}" :hidden="!(this.model.status===0 && this.model.returnType===1)">
      <a-popconfirm title="确认作废退货？" placement="topLeft" okText="是" cancelText="否" @confirm="handleUpdateStatus(3)">
        <a-button size="small" >作废退货</a-button>
      </a-popconfirm>
      <a-button type="primary" size="small" @click="handleUpdateStatus(1)">受理退货</a-button>
    </div>
    <div :style="{textAlign: 'center',marginTop: '15px'}" :hidden="!(this.model.status===0 && this.model.returnType===4)">
      <a-popconfirm title="确认作废退款？" placement="topLeft" okText="是" cancelText="否" @confirm="handleUpdateStatus(3)">
        <a-button size="small" >作废退款</a-button>
      </a-popconfirm>
      <a-button type="primary" size="small" @click="handleUpdateStatus(1)">受理退款</a-button>
    </div>
    <!--<div style="margin-top:15px;text-align: center;" :hidden="(!(this.model.status===1 && this.model.returnType===1 && (this.model.productStatus!==0 && this.model.productStatus!==4 && this.model.productStatus!==5)))">
      <a-popconfirm title="确认货品异常？" placement="topLeft" okText="是" cancelText="否" @confirm="handleUpdateReceive(5)">
        <a-button size="small" >货品异常</a-button>
      </a-popconfirm>

      <a-button type="primary" size="small" @click="handleUpdateReceive(4)">确认收货</a-button>
    </div>-->
    <div style="margin-top:15px;text-align: center;" :hidden="(!(this.model.status===1 && (this.model.moneyStatus==2 || this.model.moneyStatus==3)))">
      <a-button type="primary" size="small" @click="handleUpdateRefund(4)">退款完成</a-button>
    </div>
    <div style="margin-top:15px;text-align: center;" :hidden="(!(this.model.status===1 && (this.model.productStatus==5 && this.model.moneyStatus!=2 && this.model.moneyStatus!=3 )))">
      <a-popconfirm title="确认拒绝本次申请？" placement="topLeft" okText="是" cancelText="否" @confirm="handleUpdateKeepOn(0)">
        <a-button size="small" >拒绝本次申请</a-button>
      </a-popconfirm>
      <a-button type="primary" size="small" @click="handleUpdateKeepOn(1)">继续退款</a-button>
    </div>

  </a-drawer>
</template>

<script>

  import moment from 'moment'
  import pick from 'lodash.pick'
  import { getAction } from '@/api/manage'
  import { httpAction } from '@/api/manage'
  import DetailList from '@/components/tools/DetailList'
  import ATextarea from 'ant-design-vue/es/input/TextArea'
  const DetailListItem = DetailList.Item

  export default {
    name: 'OmsOrderReturnApplyModal',
    components: {
      ATextarea,
      DetailList,
      DetailListItem
    },
    data() {
      return {
        title:"退货申请明细",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        // 退货明细
        omsOrderReturnItemTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '商品货号',
              key: 'productSn',
              dataIndex: 'productSn'
            },
            {
              title: '商品名称',
              key: 'productName',
              dataIndex: 'productName'
            },
            {
              title: '退货数量',
              key: 'productCount',
              dataIndex: 'productCount'
            },
            {
              title: '商品单价',
              key: 'productPrice',
              dataIndex: 'productPrice'
            },
            {
              title: '商品实际支付单价',
              key: 'productRealPrice',
              dataIndex: 'productRealPrice'
            },
            {
              title: '商品条码',
              key: 'productSkuCode',
              dataIndex: 'productSkuCode'
            },
            {
              title: '商品类型',
              key: 'orderProductType_dictText',
              dataIndex: 'orderProductType_dictText'
            }
          ]
        },
        url: {
          add: "/oms/omsOrderReturnApply/add",
          editHandle: "/oms/omsOrderReturnApply/editReturnApplyHandle",
          editReceive: "/oms/omsOrderReturnApply/editReturnApplyReceive",
          editRefund: "/oms/omsOrderReturnApply/editReturnApplyRefund",
          editKeepOn: "/oms/omsOrderReturnApply/editReturnApplyKeepOn",
          queryById: "/oms/omsCompanyAddress/queryById",
          omsOrderReturnItem: {
            list: '/oms/omsOrderReturnApply/queryOmsOrderReturnItemByMainId'
          },
        }
      }
    },
    created () {
    },
    methods: {
      onDeductAmountChange(value) {
        if(value>=0){
          this.model.returnAmount = this.model.returnAmount + this.model.deductAmount - value;
          this.model.deductAmount = value;
        }
        console.log('changed', value);
      },
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;

        console.log((!(this.model.status===1 && (this.model.productStatus!==0 && this.model.productStatus!==4 && this.model.productStatus!==5))));


        if(this.model.returnAmount === null || this.model.returnAmount === "" || this.model.returnAmount === undefined)
          this.model.returnAmount = 0;

        if(this.model.deductAmount === null || this.model.deductAmount === "" || this.model.deductAmount === undefined)
          this.model.deductAmount = 0;


        if(this.model.companyAddressId === null || this.model.companyAddressId === "" || this.model.companyAddressId === undefined)
          this.model.companyAddressId = '';
        else
          this.model.companyAddressId = this.model.companyAddressId.toString();

        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'companyAddressId','handleNote', 'deductAmount', 'deductReason'))
          //时间格式化
          //this.form.setFieldsValue({handleTime:this.model.handleTime?moment(this.model.handleTime):null})
          //this.form.setFieldsValue({receiveTime:this.model.receiveTime?moment(this.model.receiveTime):null})
        });

        if (this.model.id) {
          console.log(this.model.id);
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.omsOrderReturnItem.list, params, this.omsOrderReturnItemTable)
        }

      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      requestSubTableData(url, params, tab) {
        tab.loading = true
        getAction(url, params).then(res => {
          tab.dataSource = res.result || []
        }).finally(() => {
          tab.loading = false
        })
      },

      handleChangeCompanyAddress(value){
        console.log(value);
        this.model.receiveMan = "";
        this.model.receivePhone = "";
        this.model.receiveProvince = "";
        this.model.receiveProvinceCode = "";
        this.model.receiveCity = "";
        this.model.receiveCityCode = "";
        this.model.receiveRegion = "";
        this.model.receiveRegionCode = "";
        this.model.receiveDetailAddress = "";
        if(value !== '') {
          getAction(this.url.queryById, {id:value}).then((res) => {
            if (res.success) {
              this.model.receiveMan = res.result.name;
              this.model.receivePhone = res.result.phone;
              this.model.receiveProvince = res.result.province;
              this.model.receiveProvinceCode = res.result.provinceCode;
              this.model.receiveCity = res.result.city;
              this.model.receiveCityCode = res.result.cityCode;
              this.model.receiveRegion = res.result.region;
              this.model.receiveRegionCode = res.result.areaCode;
              this.model.receiveDetailAddress = res.result.detailAddress;
            }
            console.log(res);
          })
        }
        this.model.companyAddressId = value;
      },
      handleUpdateStatus(status){
        console.log('状态',status);
        const that = this;
        if (status === 1 && this.model.returnType===1) {
          if (this.model.receiveDetailAddress === null || this.model.receiveDetailAddress === "" || this.model.receiveDetailAddress === undefined) {
            that.$message.warning("受理退货时，收货信息不可为空");
            return;
          }
        }
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = this.url.editHandle;
            let method = 'put';
            //let formData = Object.assign({}, values);
            let formData = {};
            formData.companyAddressId = this.form.getFieldValue('companyAddressId');
            formData.handleNote = this.form.getFieldValue('handleNote');

            formData.deductAmount = this.form.getFieldValue('deductAmount');
            formData.deductReason = this.form.getFieldValue('deductReason');
            formData.returnAmount = this.model.returnAmount;

            formData.id = this.model.id;
            formData.receiveMan = this.model.receiveMan;
            formData.receivePhone = this.model.receivePhone;
            formData.receiveProvince = this.model.receiveProvince;
            formData.receiveProvinceCode = this.model.receiveProvinceCode;
            formData.receiveCity = this.model.receiveCity;
            formData.receiveCityCode = this.model.receiveCityCode;
            formData.receiveRegion = this.model.receiveRegion;
            formData.receiveRegionCode = this.model.receiveRegionCode;
            formData.receiveDetailAddress = this.model.receiveDetailAddress;
            formData.status = status;

            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleUpdateReceive(productStatus){
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = this.url.editReceive;
            let method = 'put';
            //let formData = Object.assign({}, values);
            let formData = {};
            formData.receiveNote = this.form.getFieldValue('receiveNote');
            formData.id = this.model.id;
            formData.productStatus = productStatus;
            formData.deductAmount = this.form.getFieldValue('deductAmount');
            formData.deductReason = this.form.getFieldValue('deductReason');
            formData.returnAmount = this.model.returnAmount;

            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleUpdateRefund(moneyStatus){
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = this.url.editRefund;
            let method = 'put';
            //let formData = Object.assign({}, values);
            let formData = {};
            formData.id = this.model.id;
            formData.moneyStatus = moneyStatus;

            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleUpdateKeepOn(keepOnStatus){
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = this.url.editKeepOn;
            let method = 'put';
            //let formData = Object.assign({}, values);
            let formData = {};
            formData.id = this.model.id;
            formData.deductAmount = this.form.getFieldValue('deductAmount');
            formData.deductReason = this.form.getFieldValue('deductReason');
            formData.returnAmount = this.model.returnAmount;
            if(keepOnStatus === 0){
              formData.status = 3;
            } else {
              formData.moneyStatus = 2;
            }
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },

    }
  }
</script>

<style scoped>
  .title {
    color: rgba(0,0,0,.85);
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
  }
  .row {
    display: flex;
    width: 100%;
  }
  .ant-btn {
    margin-left: 30px;
    margin-bottom: 30px;
    float: right;
  }

</style>